package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.pojo.Equipment;
import com.intelligent.service.EquipmentService;
import com.intelligent.mapper.EquipmentMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
* @author lenovo
* @description 针对表【equipment(设备信息表)】的数据库操作Service实现
* @createDate 2025-09-01 14:03:08
*/
@Service
public class EquipmentServiceImpl extends ServiceImpl<EquipmentMapper, Equipment>
    implements EquipmentService{

    @Resource
    private EquipmentMapper equipmentMapper;

    /**
     * 分页查询设备（关联用户表）。
     * 仅当筛选条件非空时参与查询条件。
     */
    @Override
    public IPage<Equipment> pageEquipment(Page<Equipment> page,
                                          String equipmentCode,
                                          String equipmentName,
                                          String username,
                                          Integer status) {
        return equipmentMapper.pageEquipment(page, equipmentCode, equipmentName, username, status);
    }

    /**
     * 根据ID查询设备（关联用户表）
     */
    @Override
    public Equipment getEquipmentById(Long equipmentId) {
        return equipmentMapper.getEquipmentById(equipmentId);
    }

    /**
     * 添加设备（设备编号自动生成）
     *
     * @param equipment 设备信息
     * @return 添加成功返回true，失败返回false
     */
    @Override
    public boolean addEquipment(Equipment equipment) {
        // 生成设备编号：EQ + 当前时间戳 + 4位随机数
        String equipmentCode = generateEquipmentCode();
        equipment.setEquipemtCode(equipmentCode);

        // 设置默认状态为启用（0）
        if (equipment.getStatus() == null) {
            equipment.setStatus(0);
        }

        return equipmentMapper.addEquipment(equipment) > 0;
    }

    /**
     * 生成设备编号
     * 格式：EQ + 时间戳 + 4位随机数
     */
    private String generateEquipmentCode() {
        long timestamp = System.currentTimeMillis();
        int random = (int) (Math.random() * 10000);
        return String.format("EQ%d%04d", timestamp, random);
    }

    /**
     * 修改设备
     */
    @Override
    public boolean updateEquipment(Equipment equipment) {
        return equipmentMapper.updateEquipment(equipment) > 0;
    }

    /**
     * 删除设备
     */
    @Override
    public boolean deleteEquipment(Long equipmentId) {
        // 参数校验
        if (equipmentId == null) {
            throw new IllegalArgumentException("设备ID不能为空");
        }

        return equipmentMapper.deleteEquipment(equipmentId) > 0;
    }
}




